<template>
	<musichead class="index-musichead" name="摸摸鱼" />
	<view class="index-everyone">
		<!-- <view class="index-search">
			<input class="uni-input" />
			<text class="iconfont icon-sousu"></text>
		</view> -->
		<view class="index-card">
			<card :carddata="playLists" />
		</view>
		<view class="index-body" ref="indexBody" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
			<view class="carousel-container" :style="carouselContainerStyle">
				<view v-for="(item, index) in topList" :key="index" class="carousel-item"
					:style="getCarouselItemStyle(index)" >
					<view class="index-list-img" @click="gotoplay(item)">
						<image :src="item.coverImgUrl" mode="aspectFill"></image> <!-- 建议用 aspectFill -->
						<text>{{item.updateFrequency}}</text>
					</view>
					<view class="index-list-text" @click="gotoplay(item)">
						<view v-for="(subItem, subIndex) in item.tracks" :key="subIndex">
							{{subIndex + 1}}.{{subItem.first}} - {{subItem.second}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- <view class="index-play" @touchstart="handlePlayTouchStart" @touchend="handlePlayTouchEnd">
			<view class="play-list-container" :style="playListContainerStyle">
				<view v-for="(playlist, index) in playLists" :key="playlist.id" class="play-item"
					:style="getPlayItemStyle(index)">
					<image class="play-item-cover" :src="playlist.coverImgUrl" mode="aspectFill" />
					<view class="play-item-info">
						<text class="play-item-name">{{ playlist.name }}</text>
						<text class="play-item-creator">创建者: {{ playlist.creator.nickname }}</text>
						<text class="play-item-count">播放: {{ formatPlayCount(playlist.playCount) }}</text>
					</view>
				</view>
			</view>
		</view> -->

	</view>
	<musicbackend class="musicbackend" />
</template>

<script>
	import '@/common/iconfont.css'
	import musichead from '../../components/musichead/musichead.vue'
	import musicbackend from '../../components/musicbackend/musicbackend.vue'
	import card from '../../components/card/card.vue'
	import {
		topList,
		playList,
		register,
		searchMusic
	} from '../../common/api'
	import { baseUrl } from '../../common/config'
	export default {
		data() {
			return {
				topList: [],
				playLists: [],
				currentIndex: 0,
				isAutoPlaying: true,
				timer: null,
				itemWidth: 220,
				itemRenderWidth: 200,
				itemCount: 0,
				anglePerItem: 0,
				translateZDistance: 0,
				isLoading: false,
				hasError: false,
				errorMessage: '',
				retryCount: 0,
				hasTabBar: true
			};
		},
		onLoad() {
			// 初始化空数组
			this.topList = [];
			this.playLists = [];
			
			// 加载数据
			this.loadInitialData();
		},
		computed: {
			carouselContainerStyle() {
				if (this.itemCount === 0) return {};
				const rotateYValue = -this.currentIndex * this.anglePerItem;
				return {
					transform: `translateZ(-${this.translateZDistance}px) rotateY(${rotateYValue}deg)`,
					// 确保容器足够大以容纳旋转的子元素
					// width 和 height 可以根据需要调整，或者让子元素撑开
				};
			}
		},

		methods: {
			async loadInitialData() {
				this.isLoading = true;
				this.hasTabBar = true;
				this.hasError = false;
				this.errorMessage = '';
				
				try {
					// 并行加载数据
					const [topListData, playListData] = await Promise.all([
						this.getTopList().catch(error => {
							console.error('获取排行榜失败:', error);
							throw new Error('获取排行榜数据失败');
						}),
						this.getPlaylistsData().catch(error => {
							console.error('获取播放列表失败:', error);
							throw new Error('获取播放列表数据失败');
						})
					]);
					
					// 注册游客
					await register().catch(error => {
						console.error('游客注册失败:', error);
						throw new Error('游客注册失败');
					});
					
					// 打印数据检查
					console.log('获取到的数据:', { topListData, playListData });
					
					// 确保数据更新后重新初始化轮播图
					this.$nextTick(() => {
						this.initializeCarouselDimensions();
						this.startAutoPlay();
					});
					
				} catch (error) {
					console.error('初始化数据失败:', error);
					this.hasError = true;
					this.errorMessage = error.message || '加载数据失败，请检查网络连接';
					uni.showToast({
						title: this.errorMessage,
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.isLoading = false;
					if (this.hasError) {
						if (!this.retryCount) this.retryCount = 0;
						if (this.retryCount < 3) {
							this.retryCount++;
							console.log(`自动重试加载数据...第${this.retryCount}次`);
							setTimeout(() => {
								if (this.hasError) {
									this.loadInitialData();
								}
							}, 3000);
						} else {
							console.log('重试次数已达上限，请检查网络或服务器状态');
							uni.showToast({
								title: '重试次数已达上限，请检查网络或服务器状态',
								icon: 'none',
								duration: 3000
							});
						}
					}
				}
			},
			async gotoplay(item) {
				try {
					console.log('Playing item:', item.name);
					const word = item.name;
					if (word) {
						const songlist = await searchMusic(word);
						if (!songlist || !Array.isArray(songlist)) {
							throw new Error('Invalid song list data received');
						}
						
						// Navigate to search-result page with data
						uni.navigateTo({
							url: `/pages/search-result/search-result?songList=${encodeURIComponent(JSON.stringify(songlist))}`,
							fail: (err) => {
								console.error('Navigation failed:', err);
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								});
							}
						});
					}
				} catch (error) {
					console.error('Error in gotoplay:', error);
					uni.showToast({
						title: '获取歌曲列表失败',
						icon: 'none'
					});
				}
			},
			async getPlaylistsData() {
				try {
					const res = await playList();
					console.log('原始播放列表数据:', res);
					if (Array.isArray(res)) {
						const formattedList = res.map((item) => ({
							name: item.name || '',
							image: item.coverImgUrl || '',
							description: item.description || '暂无描述',
							signature: item.creator?.nickname || '未知创建者',
							tags: item.tags || ['音乐'],
							title: item.name || ''  // 为了匹配card组件的期望格式
						}));
						console.log('格式化后的播放列表:', formattedList);
						this.playLists = formattedList;
						return formattedList;
					}
					return [];
				} catch (error) {
					console.error('获取播放列表失败:', error);
					this.playLists = [];
					throw error;
				}
			},
			async getTopList() {
				try {
					const res = await topList();
					console.log('原始排行榜数据:', res);
					if (Array.isArray(res)) {
						this.topList = res;
						this.itemCount = this.topList.length;
						console.log('更新后的排行榜数据:', this.topList);
						console.log('更新后的itemCount:', this.itemCount);
						
						// Use this.$nextTick instead of uni.$nextTick
						await this.$nextTick();
						this.initializeCarouselDimensions();
						this.startAutoPlay();
						return res;
					}
					return [];
				} catch (error) {
					console.error('获取排行榜失败:', error);
					this.topList = [];
					this.itemCount = 0;
					throw error;
				}
			},
			initializeCarouselDimensions() {
				console.log('初始化轮播图尺寸');
				console.log('当前itemCount:', this.itemCount);
				if (this.itemCount === 0) return;

				this.itemWidth = this.itemRenderWidth + 20;
				this.calculate3DParams();
				console.log('轮播图初始化完成:', {
					itemWidth: this.itemWidth,
					anglePerItem: this.anglePerItem,
					translateZDistance: this.translateZDistance
				});
			},
			calculate3DParams() {
				if (this.itemCount === 0) return;
				this.anglePerItem = 360 / this.itemCount;
				this.translateZDistance = (this.itemRenderWidth / 2) / Math.tan(Math.PI / this.itemCount);
			},
			getCarouselItemStyle(index) {
				if (this.itemCount === 0) return {};
				const rotateYValue = index * this.anglePerItem;
				return {
					transform: `rotateY(${rotateYValue}deg) translateZ(${this.translateZDistance}px)`,
					// marginRight: '20px', // 这个margin现在不需要了，因为是绝对定位
					// width: `${this.itemRenderWidth}px` // 明确宽度
				};
			},
			setupTouchEvents() {
				// 移除旧的事件监听逻辑，改用模板中的 @touchstart 和 @touchend
			},
			handleTouchStart(e) {
				this.startX = e.touches[0].clientX;
				this.pauseAutoPlay();
			},
			handleTouchEnd(e) {
				const endX = e.changedTouches[0].clientX;
				const deltaX = endX - this.startX;
				
				if (Math.abs(deltaX) > 50) {
					if (deltaX < 0) {
						this.nextSlide();
					} else {
						this.prevSlide();
					}
				}
				this.startAutoPlay();
			},
			startAutoPlay() {
				console.log('开始自动播放');
				if (this.timer) clearInterval(this.timer);
				if (!this.isAutoPlaying || this.itemCount <= 1) return;

				this.timer = setInterval(() => {
					this.nextSlide();
				}, 3000);
			},
			pauseAutoPlay() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			nextSlide() {
				if (this.itemCount === 0) return;
				this.currentIndex = (this.currentIndex + 1) % this.itemCount;
			},
			prevSlide() {
				if (this.itemCount === 0) return;
				this.currentIndex = (this.currentIndex - 1 + this.itemCount) % this.itemCount;
			}
		},
		beforeDestroy() {
			this.pauseAutoPlay();
			// #ifdef H5
			const indexBodyEl = this.$refs.indexBody?.$el;
			if (indexBodyEl) {
				// 移除事件监听器，避免内存泄漏
				// 注意：移除时需要传入与添加时相同的函数引用，
				// 如果是匿名函数，需要先保存函数引用。
				// 为简单起见，这里不详细写移除，但在复杂应用中很重要。
			}
			// #endif
		}
	}
</script>

<style lang="scss">
	.index-musichead {
		color: #000000;
		position: absolute;
		width: 100vw;
	}

	.index-everyone {
		width: 100vw;
		height: calc(100vh - 50px);
		background-color: aliceblue;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* --- 3D Carousel Styles --- */
	.index-body {
		position: absolute; // 改为相对定位或flex子项
		bottom: 70px; // 根据上方元素调整
		width: 90vw; // 或者 100%
		// height: calc(80vh - 86px); // 这个高度可能需要调整
		height: 350px; // 给一个固定高度用于展示3D轮播
		margin-top: 0px; // 示例间距
		// background-color: #5e7e7e;
		display: flex;
		align-items: center;
		justify-content: center;
		perspective: 1200px;
		/* 视点深度，关键属性 */
		overflow: hidden;
		/* 隐藏超出部分，避免出现滚动条 */
	}

	.carousel-container {
		position: relative;
		/* 让绝对定位的子元素相对于它 */
		width: var(--item-render-width, 200px);
		/* 和 carousel-item 宽度一致 */
		height: 300px;
		/* 和 carousel-item 高度一致 */
		transform-style: preserve-3d;
		/* 关键属性：使子元素保持3D变换 */
		transition: transform 0.8s cubic-bezier(0.77, 0, 0.175, 1);
		/* 平滑过渡 */
	}

	.carousel-item {
		position: absolute;
		/* 关键：所有项叠在一起，通过transform分开 */
		top: 0;
		left: 0; // (this.itemRenderWidth - this.itemRenderWidth) / 2, 使其在容器中水平居中
		width: var(--item-render-width, 200px);
		/* 单个方块宽度，与JS中的 itemRenderWidth 对应 */
		height: 300px;
		/* 单个方块高度 */
		// margin-right: 20px; /* 在绝对定位下，margin-right 不再用于间距 */
		backface-visibility: hidden;
		/* 隐藏元素的背面，可选但推荐 */
		border: 1px solid #ccc;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		background-color: white; // 给个背景色，不然透明的
		display: flex;
		flex-direction: column;
		align-items: center;
		box-sizing: border-box;
		padding: 10px;
		overflow: hidden; // 防止内容溢出 item
	}

	.carousel-item .index-list-img {
		width: 100%; // 宽度占满 carousel-item 的 padding 内部
		height: 160px; // 调整图片区域高度
		border-radius: 5px;
		overflow: hidden;
		position: relative; // 为了 text 的绝对定位

		image {
			width: 100%;
			height: 100%;
			object-fit: cover; // 确保图片覆盖区域，不变形
		}

		text {
			position: absolute;
			left: 6px;
			bottom: 3px;
			font-size: 10px;
			color: white;
			background-color: rgba(0, 0, 0, 0.5);
			padding: 2px 4px;
			border-radius: 3px;
		}
	}

	.carousel-item .index-list-text {
		font-size: 12px;
		line-height: 1.5; // 调整行高
		margin-top: 10px;
		width: 100%;
		text-align: left; // 文本左对齐
		overflow-y: auto; // 如果文本过多，允许滚动
		max-height: calc(300px - 160px - 20px - 20px); // 总高 - 图高 - mtop - padding

		view {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-bottom: 4px;
		}
	}

	/* --- End 3D Carousel Styles --- */

	/* --- index-play 3D竖向滚动样式 --- */
	.index-play {
		width: 90vw; // 容器宽度
		max-width: 400px; // 最大宽度，避免在大屏幕上过宽
		height: 300px; // 容器高度，根据内容调整
		margin: 20px auto; // 上下边距及水平居中
		// background-color: rgba(200, 200, 255, 0.1); // 可选背景，方便调试
		display: flex;
		align-items: center;
		justify-content: center;
		perspective: 1000px; // 3D视点，重要！
		overflow: hidden; // 隐藏超出部分
		position: relative; // 用于可能的覆盖层控制
		// border: 1px solid #ccc; // 可选边框
	}

	.play-list-container {
		position: relative;
		// width: 100%; // 宽度由 .play-item 决定，或者设为和 .play-item 一致
		// height: var(--play-item-render-height, 120px); // 高度与单个item相关
		transform-style: preserve-3d;
		transition: transform 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94); // 平滑过渡
	}

	.play-item {
		position: absolute;
		// top 和 left 由JS中的transform控制原点，这里设为0让它们从容器中心开始变换
		top: calc(50% - var(--play-item-render-height, 120px) / 2); // 垂直居中变换原点
		left: 0;
		right: 0; // 宽度100%
		width: 90%; // 实际卡片宽度，相对于.play-list-container
		margin: 0 auto; // 水平居中
		height: var(--play-item-render-height, 120px); // 和JS中playItemRenderHeight一致
		background-color: white;
		border: 1px solid #eee;
		border-radius: 10px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		backface-visibility: hidden; // 隐藏背面
		display: flex;
		align-items: center;
		padding: 10px;
		box-sizing: border-box;
		cursor: pointer; // 鼠标指针样式

		&:hover {
			// 鼠标悬浮效果 (H5)
			// box-shadow: 0 6px 16px rgba(0,0,0,0.12);
			// transform: scale(1.02); // 轻微放大，但会影响3D布局，慎用
		}

		.play-item-cover {
			width: 90px; // 封面宽度 (120-2*10-10)
			height: 90px; // 封面高度
			border-radius: 8px;
			margin-right: 12px;
			flex-shrink: 0;
			object-fit: cover;
		}

		.play-item-info {
			display: flex;
			flex-direction: column;
			justify-content: center; // 垂直居中内容
			flex-grow: 1;
			height: 100%;
			overflow: hidden;

			.play-item-name {
				font-size: 15px;
				font-weight: 600;
				color: #2c3e50;
				margin-bottom: 6px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.play-item-creator,
			.play-item-count {
				font-size: 12px;
				color: #7f8c8d;
				margin-bottom: 4px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}

	/* --- 结束 index-play 样式 --- */

	.index-body::-webkit-scrollbar {
		display: none;
	}

	.musicbackend {
		position: absolute;
		z-index: 10;
	}


	.index-card {
		position: absolute;
		width: 100vw;
		height: 300px;
		top: 60px;
	}
</style>